<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="套餐名称" prop="packageName">
        <el-input
          v-model="queryParams.packageName"
          placeholder="请输入套餐名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="packageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="所属医院" prop="hospitalName" align="center"/>
      <el-table-column label="套餐名称" align="center" prop="packageName" />
      <el-table-column label="套餐描述" align="center" prop="packageDescription" />
      <el-table-column label="套餐价格" align="center" prop="price">
        <template slot-scope="scope">
          ￥{{ scope.row.price }}（元）
        </template>
      </el-table-column>
      <el-table-column label="是否可用" align="center" prop="isAvailable">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isAvailable"
            :active-value="1"
            :inactive-value="0"
            @change="handleSwitchChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleViewDetails(scope.row)"
          >查看详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 套餐表单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="体检机构" prop="hospitalId">
          <el-select
            v-model="form.hospitalId"
            filterable
            clearable
            placeholder="请选择医院"
            :loading="hospitalLoading"
            style="width: 100%"
          >
            <el-option
              v-for="hospital in hospitalOptions"
              :key="hospital.id"
              :label="hospital.name"
              :value="hospital.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="套餐名称" prop="packageName">
          <el-input v-model="form.packageName" placeholder="请输入套餐名称" />
        </el-form-item>
        <el-form-item label="套餐描述" prop="packageDescription">
          <el-input
            v-model="form.packageDescription"
            type="textarea"
            :rows="3"
            placeholder="请输入套餐描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="套餐价格" prop="price">
              <el-input-number
                v-model="form.price"
                :min="0"
                :precision="2"
                :step="100"
                controls-position="right"
                style="width: 200px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="原价" prop="originalPrice">
              <el-input-number
                v-model="form.originalPrice"
                :min="0"
                :precision="2"
                :step="100"
                controls-position="right"
                style="width: 200px"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="体检项目" prop="items">
          <el-input
            v-model="form.items"
            type="textarea"
            :rows="4"
            placeholder="请输入体检项目（多个项目用逗号分隔）"
          />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="体检时长" prop="duration">
              <el-input v-model="form.duration" placeholder="例如：2小时">
                <template slot="append">小时</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有效期" prop="validityPeriod">
              <el-input v-model="form.validityPeriod" placeholder="例如：30天">
                <template slot="append">天</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="推荐年龄" prop="recommendedAgeRange">
          <el-input v-model="form.recommendedAgeRange" placeholder="例如：18-60岁" />
        </el-form-item>
        <el-form-item label="启用状态" prop="isAvailable">
          <el-switch
            v-model="form.isAvailable"
            active-text="启用"
            inactive-text="停用"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPackage, getPackage, delPackage, addPackage, updatePackage } from "@/api/physicalExamination/package";
import { listHospital } from "@/api/hospital/hospital";

export default {
  name: "PackageManagement",
  data() {
    return {
      // 加载状态
      loading: true,
      hospitalLoading: false,

      // 选择数据
      ids: [],
      multiple: true,

      // 显示控制
      showSearch: true,
      open: false,

      // 分页数据
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        packageName: undefined
      },

      // 表单数据
      form: {},
      hospitalOptions: [],
      packageList: [],

      // 表单验证规则
      rules: {
        hospitalId: [
          { required: true, message: "请选择所属医院", trigger: "blur" }
        ],
        packageName: [
          { required: true, message: "套餐名称不能为空", trigger: "blur" },
          { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" }
        ],
        price: [
          { required: true, message: "套餐价格不能为空", trigger: "blur" },
          { type: "number", message: "必须为数字值" }
        ],
        isAvailable: [
          { required: true, message: "请选择启用状态", trigger: "change" }
        ]
      }
    };
  },
  computed: {
    title() {
      return this.form.id ? "修改体检套餐" : "新增体检套餐";
    }
  },
  created() {
    this.getList();
  },
  methods: {
    // 获取套餐列表
    async getList() {
      this.loading = true;
      try {
        const { rows, total } = await listPackage(this.queryParams);
        this.packageList = rows;
        this.total = total;
      } finally {
        this.loading = false;
      }
    },

    // 加载医院列表
    async loadHospitals() {
      this.hospitalLoading = true;
      try {
        const { rows } = await listHospital({
          pageNum: 1,
          pageSize: 1000,
          status: 1 // 只获取启用中的医院
        });
        this.hospitalOptions = rows.map(item => ({
          id: item.id,
          name: item.name
        }));
      } catch (error) {
        console.error("加载医院数据失败:", error);
        this.$modal.msgError("医院数据加载失败");
      } finally {
        this.hospitalLoading = false;
      }
    },

    // 状态切换处理
    async handleSwitchChange(row) {
      try {
        await updatePackage({
          id: row.id,
          isAvailable: row.isAvailable
        });
        this.$modal.msgSuccess("状态更新成功");
        this.getList();
      } catch (error) {
        row.isAvailable = row.isAvailable === 1 ? 0 : 1;
        this.$modal.msgError("状态更新失败");
      }
    },

    // 打开表单对话框
    async showFormDialog(row) {
      await this.loadHospitals();
      if (row?.id) {
        const { data } = await getPackage(row.id);
        this.form = data;
      } else {
        this.resetForm();
      }
      this.open = true;
    },

    // 表单提交
    async submitForm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          try {
            if (this.form.id) {
              await updatePackage(this.form);
              this.$modal.msgSuccess("修改成功");
            } else {
              await addPackage(this.form);
              this.$modal.msgSuccess("新增成功");
            }
            this.getList();
            this.open = false;
          } catch (error) {
            console.error("表单提交失败:", error);
          }
        }
      });
    },

    // 删除处理
    async handleDelete(row) {
      const ids = row.id || this.ids;
      try {
        await this.$modal.confirm(`确认删除选中的${ids.length}项记录吗？`);
        await delPackage(ids);
        this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch (error) {
        if (error !== "cancel") {
          this.$modal.msgError("删除失败");
        }
      }
    },

    // 重置表单
    resetForm() {
      this.form = {
        id: undefined,
        hospitalId: undefined,
        packageName: undefined,
        packageDescription: undefined,
        price: undefined,
        originalPrice: undefined,
        duration: undefined,
        items: undefined,
        validityPeriod: undefined,
        recommendedAgeRange: undefined,
        isAvailable: 1
      };
    },

    // 其他辅助方法
    handleAdd() {
      this.showFormDialog();
    },
    handleUpdate(row) {
      this.showFormDialog(row);
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.multiple = !selection.length;
    },
    cancel() {
      this.open = false;
      this.resetForm();
    },
    // 查看详情跳转
    handleViewDetails(row) {
      this.$router.push({
        path: '/physicalExamination/package/details',
        query: { id: row.id }
      });
    },
  }
};
</script>


